//
//  ST_BTBarrageController.swift
//  BTVideo
//
//  Created by DouLei on 2019/8/5.
//  Copyright © 2019 DouLei. All rights reserved.
//

import UIKit
import SwifterSwift
import SwiftyJSON
import HandyJSON
import MBProgressHUD
import MJRefresh

class ST_BTBarrageController: ST_BTLightBarViewController {

    var deleteClosure:(()->())?
    
  
    override func viewDidLoad() {
        super.viewDidLoad()
        
        automaticallyAdjustsScrollViewInsets = false
        
        title_nav_btn.setTitleForAllStates("弹幕管理")
        
        right_nav_btn.setImageForAllStates(ST_ImageUtils.imageName("UserCenter_mycenter_icon_未选择")!)
        
        right_nav_btn.setImage(ST_ImageUtils.imageName("UserCenter_mycenter_icon_选择"), for: UIControl.State.selected)
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(own_navigation_bar.snp.bottom)
        }
        
        tableView.backgroundColor = Color.white
        
        self.request_data()
        
    }
    
    func request_data(){
        
        currentPage += 1
        
        JVrequest(PH.barrageListApi,parameters:["page":currentPage], success: { (json) in
            
            
            
            if let list = [ST_BTBarrageInfoCellModel].deserialize(from: json["data"].rawString() ?? ""){
             
                let array = list.compactMap({$0})
                
                 if self.currentPage == 1{
                    self.data_array = array
                 }else{
                    self.data_array += array
                }
                
                self.load_more_option_style(tableView: self.tableView, count: array.count, pageSize: 15) {
                    
                    self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                        self?.request_data()
                    })
                }
                
                self.tableView.reloadData()
            }
            
            
            
            self.tableView.mj_footer?.endRefreshing()
            
        }) { (code, err) in
            self.currentPage -= 1
            
            self.tableView.mj_footer?.endRefreshing()
            
            ToastHud(text: err, view: self.view)
        }
        
    }
    
    override var hidden_right_btn: Bool {
        set {
            super.hidden_right_btn = newValue
        }
        get {
            return false
        }
    }
    
    override func right_click() {
        
        self.right_nav_btn.isSelected = !self.right_nav_btn.isSelected
        
        tableView.setEditing(self.right_nav_btn.isSelected, animated: true)
        
        if right_nav_btn.isSelected{
            
            if cancel_btn.superview == nil{

                view.addSubview(cancel_btn)
                view.addSubview(delete_btn)
                cancel_btn.snp.makeConstraints { (make) in
                    make.left.equalToSuperview().offset(38)
                    make.bottom.equalToSuperview().offset(-cancelBottomEdge)
                    make.width.equalTo(cancelBtnWidth)
                    make.height.equalTo(cancelBtnHeight)
                }
                delete_btn.snp.makeConstraints { (make) in
                    make.right.equalToSuperview().offset(-38)
                    make.bottom.equalToSuperview().offset(-cancelBottomEdge)
                    make.width.equalTo(cancelBtnWidth)
                    make.height.equalTo(cancelBtnHeight)
                }
            }
            
            cancel_btn.isHidden = false
            delete_btn.isHidden = false
            
        }else{
         
            cancel_btn.isHidden = true
            delete_btn.isHidden = true
        }
        
    }
    
//    MARK: - Properties
    var currentPage = 0
    
    lazy var tableView:UITableView = {
        
        let control = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        
        let bottomEdge = iPhoneXSeries ? BTSafeAreaBottom + 10 : 30
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: bottomEdge, right: 0)
        
        control.delegate = self
        
        control.dataSource = self
        
        control.rowHeight = UITableView.automaticDimension
        
        control.estimatedRowHeight = 92
        
        control.register(cellWithClass: ST_BTBarrageInfoCell.self)
        
        control.separatorStyle = .none
        
        control.allowsMultipleSelectionDuringEditing = true
        
        control.backgroundColor = Color.white
        //        control.backgroundColor = Color.random
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    lazy var cancelBtnWidth = (ScreenWidth - 38*2-22)/2.0
    
    lazy var cancelBtnHeight = cancelBtnWidth/140.0*36
    
    lazy var cancelBottomEdge:CGFloat = iPhoneXSeries ? 47 : 47 - 34 + 10
    
    lazy var cancel_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = Color.white
        control.cornerRadius = cancelBtnHeight/2.0
        control.borderColor = Color.init(hexString: "#42CEDA")
        control.borderWidth = 4
        control.setTitleForAllStates("取消选择")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        control.setTitleColor(Color.init(hexString: "#42CEDA")!, for: UIControl.State.normal)

        control.addTarget(self, action: #selector(cancel_handle), for: UIControl.Event.touchUpInside)
        return control
    }()

    
    
    lazy var delete_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = Color.init(hexString: "#42CEDA")
        control.cornerRadius = cancelBtnHeight/2.0
        control.setTitleForAllStates("删除")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        control.setTitleColor(UIColor.white, for: UIControl.State.normal)
        control.addTarget(self, action: #selector(didPressDelete), for: UIControl.Event.touchUpInside)
        return control
    }()

    
    var data_array = [ST_BTBarrageInfoCellModel]()
    
    
    
    
}

extension ST_BTBarrageController:UITableViewDelegate,UITableViewDataSource{
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withClass: ST_BTBarrageInfoCell.self, for: indexPath)
        
        cell.model = data_array[indexPath.row]

        return cell
    }
    
//    func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
//        if tableView.isEditing {
//            return true
//        }
//        return false
//    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        
        if tableView.isEditing {
            return true
        }
        return false
    }
    
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        
        if (editingStyle == UITableViewCell.EditingStyle.delete) {
            data_array.remove(at: indexPath.item)
            tableView.reloadData()
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if tableView.isEditing {
            return
        }
      
    }
    
}


//MARK: - Edit evnet
extension ST_BTBarrageController{
    
    @objc func didPressDelete() {
        
        
        guard let selectedRows = self.tableView.indexPathsForSelectedRows else{
            return
        }
        
        let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        hud.label.text = "请稍后"
        hud.mode = .indeterminate
        
        let idArray = selectedRows.map { (indexPath) -> String in
            return self.data_array[indexPath.row].id
        }
        
        
            
            self.right_click()
            
            let param =  ["barrage_ids":idArray.joined(separator: ",")]
            
            JVrequest(PH.deleteBarrageApi,parameters:param ,success: { (json) in
                
                self.deleteClosure?()
                
                NotificationCenter.default.post(name: Notification.Name.my_user_info_updated, object: nil)
                
                for var selectionIndex in selectedRows {
                    
                    while selectionIndex.item >= self.data_array.count {
                        selectionIndex.item -= 1
                    }
                    self.tableView(self.tableView, commit: .delete, forRowAt: selectionIndex)
                }
                hud.hide(animated: true)
                
            }) { (code, error) in
                
                hud.hide(animated: true)
                
                ToastHud(text: error, view: self.view)
            }
    }
    
    
    @objc func cancel_handle(){
        
        self.right_click()
        
    }
    
}
